package com.jy.api.service.impl;

import com.jy.api.dao.MemberAccountDao;
import com.jy.api.dao.MemberLevelDao;
import com.jy.api.domain.Member;
import com.jy.api.domain.MemberAccount;
import com.jy.api.domain.MemberLevel;
import com.jy.api.service.MemberLevelService;
import com.jy.api.signUpReq.admin.BillRuleReq;
import com.jy.api.signUpReq.admin.MemberLevelReq;
import com.jy.api.util.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by xiaohua on 2019/4/29.
 */
@Service
public class MemberLevelServiceImpl implements MemberLevelService {

    @Autowired
    private MemberLevelDao levelDao;
    @Autowired
    private MemberAccountDao accountDao;

    @Override
    public List<MemberLevel> findLevelList(String storeId) {
        return levelDao.findAllByStoreIdAndEnabled(storeId, true);
    }

    @Override
    @Transactional
    public void deleteById(int id) {
        MemberLevel level = levelDao.findOne(id);
        MemberAccount memberAccount = accountDao.findByStoreIdAndLevelIdAndEnabled(level.getStoreId(), id, true);
        if (level != null) {
            level.setEnabled(false);
            if (memberAccount != null) {
                memberAccount.setLevelId(0);
            }
        }
        levelDao.save(level);
        accountDao.save(memberAccount);
    }

    @Override
    public Result updateOrSave(MemberLevelReq req) {
        MemberLevel level;
        if (0 == req.getId()) {
            level = new MemberLevel();
            BeanUtils.copyProperties(req, level);
            if (req.isStartLevel()) {
                MemberLevel memberLevel = levelDao.findByStoreIdAndAndStartLevel(req.getStoreId(), true);
                if (memberLevel != null) {
                    memberLevel.setStartLevel(false);
                    levelDao.save(memberLevel);
                }
            }
        } else {
            level = levelDao.findOne(req.getId());
            if (req.isStartLevel()) {
                MemberLevel memberLevel = levelDao.findByStoreIdAndAndStartLevel(req.getStoreId(), true);
                if (memberLevel != null) {
                    memberLevel.setStartLevel(false);
                    levelDao.save(memberLevel);
                }
            }
            BeanUtils.copyProperties(req, level);
        }
        levelDao.save(level);
        return new Result(200, "操作成功！");
    }
}
